package dao

import (
	"github.com/go-xorm/xorm"
	"log"
	"lottery/models"
)

type AwardDao struct {
	engine *xorm.Engine
}

func NewAwardDao(engine *xorm.Engine) *AwardDao {
	return &AwardDao{engine: engine}
}

func (d *AwardDao) Get(id int) *models.TbAward {
	data := &models.TbAward{Id: id}
	ok, err := d.engine.Get(data)
	if ok && err == nil {
		return data
	} else {
		data.Id = 0
		return data
	}
}

func (d *AwardDao) GetAll() []models.TbAward {
	dataList := make([]models.TbAward, 0)
	err := d.engine.Find(&dataList)
	if err != nil {
		log.Println("award_dao.GetAll() failed, err=", err)
	}
	return dataList
}

func (d *AwardDao) GetByEvent(eventId int) []models.TbAward {
	dataList := make([]models.TbAward, 0)
	err := d.engine.
		Where("event_id=?", eventId).
		Desc("weight").
		Desc("id").
		Find(&dataList)
	log.Println("award_dao.GetByEvent() failed, err=", err)
	return dataList
}

func (d *AwardDao) CountAll() int64 {
	count, err := d.engine.Count(&models.TbAward{})
	if err != nil {
		log.Println("award_dao.CountAll() failed, err=", err)
		return 0
	}
	return count
}

func (d *AwardDao) CountByEvent(eventId int) int64 {
	count, err := d.engine.
		Where("event_id=?", eventId).
		Count(&models.TbAward{})
	if err != nil {
		log.Println("award_dao.CountByEvent() failed, err=", err)
		return 0
	}
	return count
}

func (d *AwardDao) Update(data *models.TbAward, columns []string) error {
	_, err := d.engine.Id(data.Id).MustCols(columns...).Update(data)
	return err
}

func (d *AwardDao) Create(data *models.TbAward) error {
	_, err := d.engine.Insert(data)
	return err
}

func (d *AwardDao) DecrLeftNum(id, num int) (i int64, e error) {
	i, e = d.engine.Id(id).
		Decr("rest_amount", num).
		Where("rest_amount>=?", num).
		Update(&models.TbAward{Id: id})
	return
}
